import { getUserInfo } from '@/api/user'
import { RootState } from '@/store'
import { User } from '@/types/user'
import { useEffect, useState } from 'react'
// import { useNavigate } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import { useNavigate, useLocation } from 'react-router-dom'
import { Button, Dialog, List } from 'antd-mobile'

import styles from './index.module.scss'
import { setInfo } from '@/store/modules/user'

export default function My () {
  const user = useSelector((state: RootState) => state.user)
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const location = useLocation()

  const [userInfo, setUserInfo] = useState({} as User)

  const getUserInfoData = async () => {
    const res = await getUserInfo()
    setUserInfo(res.data)
  }

  const logout = () => {
    Dialog.show({
      content: (
        <div>
          <h3 style={{ textAlign: 'center' }}>提示</h3>
          <div style={{ height: 30, textAlign: 'center', paddingTop: 10 }}>
            你确定退出吗?
          </div>
        </div>
      ),
      closeOnAction: true,
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
            style: {
              color: 'black'
            }
          },
          {
            key: 'commit',
            text: '确定',
            danger: true,
            onClick: () => {
              // 清除token
              dispatch(setInfo({}))
              // 跳转到登录页面
              navigate(`/login`)
            }
          }
        ]
      ]
    })
  }

  useEffect(() => {
    if (!user.token) {
      // console.log(location)
      

      // navigate(`/login?redirect=${location.pathname}`)
    }
    getUserInfoData()
  }, [])

  return (
    <div className={styles.content}>
      <div className={styles.header}>
        <img className={styles.img} src={userInfo.avatar} alt='' />
        <p className={styles.nickname}>{userInfo.username}</p>
      </div>
      <List>
        <List.Item onClick={() => {}}>会员中心</List.Item>
        <List.Item onClick={() => {}}>我的订单</List.Item>
        <List.Item onClick={() => {}}>收货地址</List.Item>
        <List.Item onClick={() => {}}>我的足迹</List.Item>
        <List.Item onClick={() => {}}>我的收藏</List.Item>
        <List.Item onClick={() => {}}>意见反馈</List.Item>
      </List>
      <div className={styles.footer}>
        <Button shape='rounded' block color='primary' onClick={logout}>
          退出
        </Button>
      </div>
    </div>
  )
}
